package sige

import org.springframework.dao.DataIntegrityViolationException

class AlunoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        def lista = []
        println ("${params}")
        params.max = Math.min(max ?: 10, 100)
        boolean ativosInstance =  params.ativos
        def campoInstance = params.campo ?: ""
        if(  ativosInstance ){
            lista = Aluno.findAllByNomeIlikeAndAtivo("%${campoInstance}%", true,
                [ max: params.max, sort: params.sort, order: params.order, offset: params.offset ])
        }else{
            lista = Aluno.findAllByNomeIlike("%${campoInstance}%",
                [ max: params.max, sort: params.sort, order: params.order, offset: params.offset ])
        }
        [alunoInstanceList: lista, alunoInstanceTotal: lista.size(),
            ativosInstance: ativosInstance, campoInstance: campoInstance]
    }

    def create(Long id) {
        def alunoInstance
        if( id || alunoInstance?.id ){
            alunoInstance = Aluno.get(id)
        }else{
            alunoInstance = new Aluno(params)
        }
        
        [alunoInstance: alunoInstance]
    }

    def save() {
        def alunoInstance = new Aluno(params)
        if (! alunoInstance.dadosDoAluno.save() || !alunoInstance.save(flush: true)) {
            render(view: "create", model: [alunoInstance: alunoInstance])
            return
        }
        upload(alunoInstance)
        flash.message = message(code: 'aluno.passo.message', args: ['1'])
        redirect(action: "create_1", id: alunoInstance.id)
    }
    
    def upload(def alunoInstance){
        println ("transferindo a foto ...")
        def f = request.getFile("arquivo")
        if(!f.empty){
            f.transferTo(new File(servletContext.getRealPath("images/alunos/${alunoInstance.id.toString()}")))
        }else{
            println ("Não transferiu")
            flash.message = "não foi possível transferir o arquivo. Tente novamente mais tarde :)"
        }
        println ("Foto transferida")
    }
    
    def create_1(Long id) {
        def alunoInstance = Aluno.get(id)
        if(alunoInstance?.dadosDoRegistro && params){
            alunoInstance?.dadosDoRegistro.properties = params
        }
        [ alunoInstance: alunoInstance ]
    }
    
    def save1(Long alunoId, Long alunoVersion) {
        Aluno alunoInstance = Aluno.get(alunoId)
        def dadosDoRegistroInstance
        if(alunoInstance.dadosDoRegistro){
            dadosDoRegistroInstance = alunoInstance.dadosDoRegistro
        }else{
            dadosDoRegistroInstance = new DadosDoRegistro(params)
        }
        
        
        if (alunoVersion != null) {
            if (alunoInstance.version > alunoVersion) {
                alunoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'aluno.label', default: 'Aluno')] as Object[],
                          "Another user has updated this Aluno while you were editing")
                render(view: "create_1", model: ['id':alunoInstance.id, 'params': params ] )
                return
            }
        }
        
        alunoInstance.dadosDoRegistro = dadosDoRegistroInstance
        if (!dadosDoRegistroInstance.save() || !alunoInstance.save(flush: true)) {
            render(view: "create_1", model: ['id':alunoInstance.id, 'params': params ] )
            return
        }

        flash.message = message(code: 'aluno.passo.message', args: ['2'])
        redirect(action: "create_2", id: alunoInstance.id)
    }
    
    def create_2(Long id) {
        def alunoInstance = Aluno.get(id)
        if(alunoInstance?.dadosFamiliares && params){
            alunoInstance.dadosFamiliares.properties = params
        }
        [alunoInstance: alunoInstance]
    }
    
    def save2(Long alunoId, Long alunoVersion) {
        def dadosFamiliaresInstance = new DadosFamiliares(params)
        Aluno alunoInstance = Aluno.get(alunoId)
        
        if (alunoVersion != null) {
            if (alunoInstance.version > alunoVersion) {
                alunoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'aluno.label', default: 'Aluno')] as Object[],
                          "Another user has updated this Aluno while you were editing")
                render(view: "create_2", model: ['id': alunoInstance.id, 'params': params])
                return
            }
        }
        
        alunoInstance.dadosFamiliares = dadosFamiliaresInstance
        if (!dadosFamiliaresInstance.save() || !alunoInstance.save(flush: true)) {
            render(view: "create_2", model: ['id': alunoInstance.id, 'params': params])
            return
        }

        flash.message = message(code: 'aluno.passo.message', args: ['3'])
        redirect(action: "create_3", id: alunoInstance.id)
    }
    
    def create_3(Long id) {
        def historicoDeSaudeInstance
        def alunoInstance = Aluno.get(id)
        if(alunoInstance?.historicoDeSaude && params){
            alunoInstance.historicoDeSaude.properties = params
        }
        [alunoInstance: alunoInstance]
    }
    
    def save3(Long alunoId, Long alunoVersion) {
        def historicoDeSaudeInstance = new HistoricoDeSaude(params)
        Aluno alunoInstance = Aluno.get(alunoId)
        
        if (alunoVersion != null) {
            if (alunoInstance.version > alunoVersion) {
                alunoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'aluno.label', default: 'Aluno')] as Object[],
                          "Another user has updated this Aluno while you were editing")
                render(view: "create_3", model: ['id': alunoInstance.id, 'params': params])
                return
            }
        }
        
        alunoInstance.historicoDeSaude = historicoDeSaudeInstance
        if (!historicoDeSaudeInstance.save() || !alunoInstance.save(flush: true)) {
            render(view: "create_3", model: ['id': alunoInstance.id, 'params': params])
            return
        }

        flash.message = message(code: 'aluno.passo.message', args: ['4'])
        redirect(action: "create_4", id: alunoInstance.id)
    }
    
    def create_4(Long id) {
        def alunoInstance = Aluno.get(id)
        def alunosTransferidosInstance
        if(alunoInstance?.alunosTransferidos){
            alunosTransferidosInstance = alunoInstance.alunosTransferidos
        }else{
            alunosTransferidosInstance = new AlunosTransferidos(params)
        }
        [alunoInstance: alunoInstance , alunosTransferidosInstance : alunosTransferidosInstance]
    }
    
    def save4(Long alunoId, Long alunoVersion) {
        def alunosTransferidosInstance = new AlunosTransferidos(params)
        Aluno alunoInstance = Aluno.get(alunoId)
        
        if (alunoVersion != null) {
            if (alunoInstance.version > alunoVersion) {
                alunoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'aluno.label', default: 'Aluno')] as Object[],
                          "Another user has updated this Aluno while you were editing")
                render(view: "create_4", model: [alunoInstance: alunoInstance])
                return
            }
        }
        
        alunoInstance.alunosTransferidos = alunosTransferidosInstance
        if (!alunosTransferidosInstance.save() || !alunoInstance.save(flush: true)) {
            render(view: "create_4", model: [alunoInstance: alunoInstance , alunosTransferidosInstance: alunosTransferidosInstance])
            return
        }

        flash.message = message(code: 'aluno.passo.message', args: ['5'])
        redirect(action: "show", id: alunoInstance.id)
    }

    def show(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }

        [alunoInstance: alunoInstance]
    }

    def edit(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }
        def dadosDoAlunoInstance
        if( !alunoInstance?.dadosDoAluno){
            alunoInstance?.dadosDoAluno = new DadosDoAluno(params)
        }
        [alunoInstance: alunoInstance, dadosDoAlunoInstance: alunoInstance?.dadosDoAluno]
    }
    
    def edit_1(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }
        def ddr
        if(alunoInstance?.dadosDoRegistro){
            ddr = alunoInstance?.dadosDoRegistro
        }else{
            ddr = new DadosDoRegistro(params)
        }
        [alunoInstance: alunoInstance , dadosDoRegistroInstance : ddr]
    }
    
    def edit_2(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }
        def dadosFamiliaresInstance
        if(alunoInstance?.dadosFamiliares){
            dadosFamiliaresInstance = alunoInstance?.dadosFamiliares
        }else{
            dadosFamiliaresInstance = new DadosFamiliares(params)
        }
        [alunoInstance: alunoInstance , dadosFamiliaresInstance : dadosFamiliaresInstance]
    }
    
    def edit_3(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }
        def historicoDeSaudeInstance
        if(alunoInstance?.historicoDeSaude){
            historicoDeSaudeInstance = alunoInstance?.historicoDeSaude
        }else{
            historicoDeSaudeInstance = new HistoricoDeSaude(params)
        }
        [alunoInstance: alunoInstance , historicoDeSaudeInstance : historicoDeSaudeInstance ]
    }
    
    def edit_4(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }
        def alunosTransferidosInstance
        if(alunoInstance?.alunosTransferidos){
            alunosTransferidosInstance = alunoInstance?.alunosTransferidos
        }else{
            alunosTransferidosInstance = new AlunosTransferidos(params)
        }
        [alunoInstance: alunoInstance , alunosTransferidosInstance : alunosTransferidosInstance ]
    }

    def update(Long id, Long version) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (alunoInstance.version > version) {
                alunoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'aluno.label', default: 'Aluno')] as Object[],
                          "Another user has updated this Aluno while you were editing")
                render(view: "edit", model: [alunoInstance: alunoInstance])
                return
            }
        }
        
        println "$params"
        alunoInstance.properties = params
        
        alunoInstance?.dadosDoAluno?.properties = params
        alunoInstance?.dadosDoAluno?.save()
        alunoInstance?.dadosDoRegistro?.properties = params
        alunoInstance?.dadosDoRegistro?.save()
        alunoInstance?.dadosFamiliares?.properties = params
        alunoInstance?.dadosFamiliares?.save()
        alunoInstance?.historicoDeSaude?.properties = params
        alunoInstance?.historicoDeSaude?.save()
        alunoInstance?.alunosTransferidos?.properties = params
        alunoInstance?.alunosTransferidos?.save()

        if (!alunoInstance.save(flush: true)) {
            render(view: "edit", model: [alunoInstance: alunoInstance])
            return
        }
        
        

        flash.message = message(code: 'default.updated.message', args: [message(code: 'aluno.label', default: 'Aluno'), alunoInstance.id])
        redirect(action: "show", id: alunoInstance.id)
    }

    def delete(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }

        try {
            alunoInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "show", id: id)
        }
    }
    
    def imprime(Long id) {
        def alunoInstance = Aluno.get(id)
        if (!alunoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'aluno.label', default: 'Aluno'), id])
            redirect(action: "list")
            return
        }

        [alunoInstance: alunoInstance]
    }
    
    def updateSeries = {

        def series
        try{
            long id = Long.parseLong(params.id)
            def ano =  AnoLetivo.get(id)

            series = ano.series
        }catch (e){
            println e
            
        }
        render (template: 'selectAjax', model:[selectList: series, 
                messageCode: 'serie.label', propName: 'serie.id',
                action: 'updateTurmas', updateme: 'turmas'])
    }
    
    def updateTurmas = {
        def turmas
        try{
            long id = Long.parseLong(params.id)
            def serie =  Serie.get(id)

            turmas = serie.turmas
        }catch (e){
            println e
        }
        render (template: 'selectTurma', model:[turmaList: turmas, 
                messageCode: 'turma.label' ])
    }
}
